package com.woniuxy.kaer.tenants.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.kaer.commons.util.Data;
import com.woniuxy.kaer.commons.util.MD5Util;
import com.woniuxy.kaer.commons.util.SMSUtil;
import com.woniuxy.kaer.redis.util.RedisKey;
import com.woniuxy.kaer.tenants.dto.FoundInfoDto;
import com.woniuxy.kaer.tenants.dto.FounderDto;
import com.woniuxy.kaer.tenants.entity.Founder;
import com.woniuxy.kaer.tenants.mapper.FounderMapper;
import com.woniuxy.kaer.tenants.param.TenantsLoginParam;
import com.woniuxy.kaer.tenants.param.TenantsRegisterParam;
import com.woniuxy.kaer.tenants.service.FounderService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 程诗洋
 * @since 2025年02月17日
 */
@Service
public class FounderServiceImpl extends ServiceImpl<FounderMapper, Founder> implements FounderService {

    @Resource
    private FounderMapper founderMapper;
    @Resource
    private SMSUtil smsUtil;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;
    @Override
    public FounderDto tenantsLogin(TenantsLoginParam param) throws Exception {
        QueryWrapper<Founder> founderQueryWrapper = new QueryWrapper<>();
        founderQueryWrapper.eq("register_mobile",param.getRegisterMobile());
        Founder founder = founderMapper.selectOne(founderQueryWrapper);
        if(null==founder){
            throw new Exception("用户不存在");
        }
        if(!founder.getFounderPass().equals(MD5Util.md5(param.getFounderPass(), param.getRegisterMobile()))){
            throw new Exception("密码错误");
        }
        FounderDto founderDto = BeanUtil.toBean(founder, FounderDto.class);
        return founderDto;
    }

    @Override
    public void tenantsRegister(TenantsRegisterParam param) throws Exception {
        System.out.println(param.getRegisterCode());
        System.out.println(stringRedisTemplate.opsForValue().get(RedisKey.REGISTER_CODE_KEY(param.getRegisterMobile())));
        if(!stringRedisTemplate.opsForValue().get(RedisKey.REGISTER_CODE_KEY(param.getRegisterMobile())).equals(param.getRegisterCode())){
            throw new Exception("验证码不正确");
        }

        RLock lock1 = redissonClient.getFairLock(RedisKey.LOCK_TENANTS_MOBILE_BUSS(param.getRegisterMobile())+"tenantsRegister");
        lock1.lock();
        try {
            QueryWrapper<Founder> founderQueryWrapper = new QueryWrapper<>();
            founderQueryWrapper.eq("register_mobile", param.getRegisterMobile());
            founderQueryWrapper.ne("founder_state", Data.FOUNDER_STATE_DELETE);
            Founder founder = founderMapper.selectOne(founderQueryWrapper);
            if(null!=founder){
                throw new Exception("账户已存在");
            }
            Founder founder1 = BeanUtil.toBean(param, Founder.class);
            founder1.setRegisterTime(LocalDateTime.now());
            founder1.setFounderPass(MD5Util.md5(param.getFounderPass(), param.getRegisterMobile()));
            founder1.setFounderState(Data.FOUNDER_STATE_NORMAL);
            founderMapper.insert(founder1);

            stringRedisTemplate.delete(RedisKey.REGISTER_CODE_KEY(param.getRegisterMobile()));
        }finally {
            lock1.unlock();
        }
    }

    @Override
    public void sendRegisterCode(String mobile) throws Exception {
        //0.判断一分钟内是否发送过验证码
        if (stringRedisTemplate.hasKey(RedisKey.REGISTER_CODE_STATE(mobile))) {
            throw new Exception("发送过于频繁，请稍后再试");
        }
        //1.去重
        QueryWrapper<Founder> founderQueryWrapper = new QueryWrapper<>();
        founderQueryWrapper.eq("register_mobile", mobile);
        Founder founder = founderMapper.selectOne(founderQueryWrapper);
        if(null!=founder){
            throw new Exception("手机号重复");
        }
        //?还要验证身份证号码
        //2.发送验证码
        String code = Integer.toString(smsUtil.sendCode(mobile));
        //3.存入redis
        stringRedisTemplate.opsForValue().set(RedisKey.REGISTER_CODE_KEY(mobile), code, 300, TimeUnit.SECONDS);
        //4.保存一个key,有效期为一分钟
        stringRedisTemplate.opsForValue().set(RedisKey.REGISTER_CODE_STATE(mobile), "", 60, TimeUnit.SECONDS);
    }

    @Override
    public FoundInfoDto getFounderById(Integer founderId) throws Exception {
        Founder founder = founderMapper.selectById(founderId);
        if(null==founder){
            throw new Exception("商家不存在");
        }
        if(founder.getFounderState()!=Data.FOUNDER_STATE_NORMAL){
            throw new Exception("商家状态异常");
        }
        FoundInfoDto founderInfoDto = BeanUtil.toBean(founder, FoundInfoDto.class);
        return founderInfoDto;
    }
}
